package com.gitee.feizns.quickstart.log;

import lombok.Data;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 操作日志
 * @author feizns
 * @since 2024/2/25
 */
@Data
public class MethodLog {

    /**
     * 操作类型
     */
    private String type;

    /**
     * 操作描述
     */
    private String description;

    /**
     * 请求参数
     */
    private Object[] args;

    /**
     * 返回结果值
     */
    private Object result;

    /**
     * 异常信息
     */
    private Throwable exception;

    /**
     * 操作时间
     */
    private LocalDateTime time;

    /**
     * 用户ID
     */
    private Object userid;

    /**
     * 是否执行成功
     * @return boolean
     */
    public boolean isSuccessful() {
        return exception == null;
    }

    /**
     * 执行上下文
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public Map<String, Object> context() {
        Map<String, Object> context = new LinkedHashMap<>();
        context.put("type", type);
        context.put("args", args);
        context.put("result", result);
        context.put("exception", exception);
        context.put("time", time);
        return context;
    }

    /**
     * 有异常
     * @return boolean
     */
    public boolean hasException() {
        return exception != null;
    }

    /**
     * 错误信息
     * @return {@link String}
     */
    public String exceptionMessage() {
        return exception.getMessage();
    }

    /**
     * 错误信息
     * @return {@link String}
     */
    public String printStackTraceMessage() {
        StringWriter writer = new StringWriter();
        exception.printStackTrace(new PrintWriter(writer));
        return writer.toString();
    }

}